package cn.cvs.config.shiro;

import cn.cvs.mapper.SysUserPlusMapper;
import cn.cvs.pojo.SysRight;
import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.RoleShiroService;
import cn.cvs.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    SysUserPlusMapper userPlusMapper;
    @Resource
    RoleShiroService roleShiroService;
    @Override
    //获取权限信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("shiro >>>> 获取<<权限>>信息");
        SysUser user= (SysUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //授权逻辑
        //静态授权:授予主体(用户) 相应的角色和权限
      /*  info.addRole(user.getSysRole().getRoleName());
        info.addStringPermission("用户列表");
        if ("管理员".equals(user.getSysRole().getRoleName())){
            info.addStringPermission("用户添加");
            info.addStringPermission("用户编辑");
            info.addStringPermission("useredit");
            info.addStringPermission("用户删除");
        }*/

        //动态授权
        //动态获取权限列表
        //动态获取该用户的权限(登录时传入)
        SysRole role = user.getRole();
        if (null!=role){
            info.addRole(role.getRoleName());
            List<SysRight> rights = role.getRights();
            if (null!=rights && rights.size()>0){
                rights.forEach(sysRight -> info.addStringPermission(sysRight.getRightCode()));
            }
        }


        return info;
    }

    @Override
    //获取身份信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("shiro >>>> 获取身份信息");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        //SysUser user = userService.getUserByName(usrName);  //查询用户及角色id
        //查询语句关联 role对象
        SysUser user = userPlusMapper.getByUsrNameSysUserAndRole(usrName); //查询用户及角色信息
        if (null == user){
            throw new UnknownAccountException();//账号错误
        }
        if (user.getUsrFlag()==null || user.getUsrFlag().intValue()==0){
            throw new LockedAccountException();//账号锁定
        }
        //SimpleAuthenticationInfo(身份|按账密查得的数据库用户,凭证|数据库返回的密码,realm的名称)
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getUsrPassword(),getName());
        return info;
    }
}
